<?php
namespace app\services;

use app\common\model\Gameagent;
use think\Db;
use app\common\model\Order;
use app\common\model\CpChannel;
use app\common\model\Gamelist;
use app\common\model\SettlementOrder;
use app\common\model\Channel;
use app\common\model\Stat;
use app\common\model\SettlementGame;


class Settlement
{
    /**
     * 执行统计
     */
    public function settlement()
    {
        /**
         * 定时任务对上月订单进行结算
         */

        $where = [];
        // 查询上月订单
        $where[] =['pay_time', 'between', [date('Y-m-01 00:00:00', strtotime('-1 month')), date('Y-m-t 23:59:59', strtotime('-1 month'))]];
        $where[] =['order_status', '=', 3];

        // 渠道数据
        $channel = Channel::where('status', 1)->column('fee','id');

        // 查询游戏列表
        $cp = new CpChannel();
        $orderList = $cp->alias('c')
            ->field('c.id,c.name,g.id as gid,g.name as gname,	g.gfencheng,g.cfencheng,o.cid,o.order_no,o.amount')
            ->join('gamelist g', 'c.id=g.gchannel')
            ->join('order o', 'g.id=o.gid')
            ->where($where)
            ->select();
        foreach ($orderList as $v) {
            $fee = $channel[$v['cid']] ?? 0;

            $g_fencheng = $v['amount'] * $v['gfencheng'] / 100;
            $c_fencheng = $v['amount'] * $fee / 100;
            $g_fee = $g_fencheng * $v['cfencheng'] / 100;
            $g_fencheng = $g_fencheng - $g_fee;
            $settle = [
                'order_no' => $v['order_no'],
                'gid' => $v['gid'],
                'cid' => $v['cid'],
                'cp_id' => $v['id'],
                'date_month' => date('Y-m', strtotime('-1 month')),
                'amount' => $v['amount'],
                'g_fencheng' => $g_fencheng,// 游戏分成
                'c_fencheng' => $c_fencheng,// 渠道分成
                'g_fee' => $g_fee, // 通道费
                'status' => 0,
            ];
            $order = new SettlementOrder();
            $order->updateSettleOrder($settle);

        }
    }

    public function settlement_month(){

        // 查询上月订单
        $stat = new Stat();
        $where = [];
        $startTime = date('Y-m-01', strtotime('-1 month')).' 00:00:00';
        $endTime = date('Y-m-t', strtotime('-1 month')) . ' 23:59:59';

        $channels = Channel::where(["status"=>1,'id'=>5])->column('id');

//        array_unshift($channels, 0);
        $gameAgents = Gamelist::alias('g')->whereIn('g.gstatus', [1])// 1 上线 2 测试中
        ->where(['g.id'=>30])
        ->field('g.id,g.gfencheng,g.cfencheng,g.gchannel,c.id as cp_id')
        ->join('cp_channel c', 'c.id=g.gchannel')
        ->select();

        foreach ($channels as $cid){
            foreach ($gameAgents as $gid) {

                $orderSettle = $this->getOrderSettle($cid, $gid, $startTime, $endTime);

                $g_fencheng = $orderSettle['g_fencheng'];
                $c_fencheng = $orderSettle['c_fencheng'];
                $g_fee = $orderSettle['g_fee'];

                $settle = [
                    'gid' => $gid['id'],
                    'cid' => $cid,
                    'cp_id' => $gid['cp_id'],
                    'date_month' => date('Y-m', strtotime('-1 month')),
                    'amount' => $orderSettle['total_amount'],
                    'g_fencheng' => $g_fencheng,// 游戏分成
                    'c_fencheng' => $c_fencheng,// 渠道分成
                    'g_fee' => $g_fee, // 通道费
                    'status' => 0,
                ];
                // 检查是否所有统计指标都为0
                if (!$this->isAllZero($settle)) {
                    $order = new SettlementGame();
                    $order->updateSettleGame($settle);


                }

            }
        }
    }


    /**
     * 获取订单统计
     * @param int $cid 渠道ID(0表示系统用户)
     * @param int $gid 游戏ID
     * @param int $startTime 开始时间戳(当天00:00:00)
     * @param int $endTime 结束时间戳(当天23:59:59)
     * @return array
     */
    protected function getOrderSettle($cid, $gid, $startTime, $endTime)
    {

        // 查询游戏代理信息
        $agent = Gameagent::where(['gid'=>$gid['id'],'cid'=>$cid])->find();
        // 渠道分成
        if(!empty($agent)){
            $fee = $agent['fencheng'];
            $tongdao = $agent['tongdao'];
        }else{
            $fee = 0;
            $tongdao = 0;
        }
        $tongdao = $gid['cfencheng'] ?? 0;

        // 使用模型的数据库连接
        $orderModel = new Order();
        // 付费总金额
        $payAmount = $orderModel->where('gid', $gid['id'])
            ->where('cid', $cid)
            ->where('order_status', '=', 3)
            ->whereBetweenTime('pay_time', $startTime, $endTime)
            ->sum('amount');

        $g_fencheng = $payAmount * $gid['gfencheng'] / 100;// 游戏分成
        $c_fencheng = $payAmount * $fee / 100; // 渠道分成
        $g_fee = $g_fencheng * $tongdao / 100;
        $g_fencheng = $g_fencheng - $g_fee; // 游戏分成 减去通道费

        return [
            'total_amount' => $payAmount ?: 0,
            'g_fencheng' => $g_fencheng ?: 0,
            'c_fencheng' => $c_fencheng ?: 0,
            'g_fee' => $g_fee ?: 0,
        ];
    }


    /**
     * 判断统计结果是否全部为0
     * @param array $statData
     * @return bool
     */
    protected function isAllZero(array $statData): bool
    {
        $checkFields = [
            'amount',
            'g_fencheng',
            'c_fencheng',
            'g_fee'
        ];

        foreach ($checkFields as $field) {
            if (!empty($statData[$field])) {
                return false;
            }
        }

        return true;
    }

}